package com.hdl.servlet.cart;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdl.entity.MallCart;

/**
 * CartItemNumServlet 获取购物车中商品项的数量
 * @author Administrator
 *
 */
@WebServlet("/cartItemNum.let")
public class CartItemNumServlet extends HttpServlet{
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//从session中获取购物车
		MallCart cart = (MallCart) req.getSession().getAttribute("cart");
		Map<String,Object> map = new HashMap<String,Object>();
		
		//判断购物车是否存在
		if(cart == null) {//不存在
			map.put("num", "");//空
		}else {
			map.put("num",cart.getList().size());//放入购物车的购物项的数量
		}
		
		//将数据写回
		ObjectMapper mapper = new ObjectMapper();
		mapper.writeValue(resp.getOutputStream(), map);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}
